<?php

namespace App\Services;
use App\Admin\Actions\ExchangeCode;
use App\Models\ExchangeCodeModel;
use App\Models\UserModel;
use Framework\Hope;
use Framework\Jwt;
use Framework\ModelEncryptionTrait;
use GuzzleHttp\Client;
use Framework\BaseService;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;


class AuthService  extends BaseService
{


    use ModelEncryptionTrait;
    private $jwt;

    public function __construct(Jwt $jwt)
    {
        $this->jwt = $jwt;
    }

    /**
     * 小程序登录
     * @param $code
     */
    public function minlogin($code,$shared_user_id,$iv,$encryptedData)
    {
        if($shared_user_id){
           $flg =  UserModel::query()->where('id',$shared_user_id)->first();
           if(!$flg){
                $this->retError("分享信息异常");
           }
        }
        $app = app('wechat.mini_program');
        $wechat = $app->auth->session($code);

        if(!isset($wechat['openid']))
        {
            $this->retError('code无效');
        }
        $decryptedData = $app->encryptor->decryptData($wechat['session_key'], $iv, $encryptedData);
//        $nickname = $decryptedData['nickName'];
        $avatarUrl = $decryptedData['avatarUrl'];

        $user = UserModel::query()->where(['min_openid'=>$wechat['openid']])->first();
        if(!$user){
            $molde = new UserModel();
            $molde->min_openid = $wechat['openid'];
            $molde->nickname = "微信用户".rand(1,99999);
            $molde->avatar = $avatarUrl;
            $molde->pid = isset($shared_user_id) ? $shared_user_id : 0;
            $molde->invite_code =  Hope::makeInviterCode();
            $molde->saveOrFail();

            if($molde && isset($shared_user_id)){
                //随机给邀请人和被邀请人分配一个优惠券
                $time = Carbon::now();
                ExchangeCodeModel::query()->where('status',0)->inRandomOrder()->update(['user_id'=>$shared_user_id,'receive_time'=>$time]);
                ExchangeCodeModel::query()->where('status',0)->inRandomOrder()->update(['user_id'=>$molde->id,'receive_time'=>$time]);
            }

            $jwt_str = $this->jwt->getToken((string)$molde->id);
            $arr = array(
                'jwt' => $jwt_str, 'user_id' => $molde->id
            );

            return $arr;
        }else{
            $jwt_str = $this->jwt->getToken((string)$user->id);
            $arr = array(
                'jwt' => $jwt_str, 'user_id' => $user->id
            );
            return $arr;
        }




    }






}
